class MyPromise {
  // 构造函数接收执行器函数
  constructor(executor) {
    // 初始化状态为等待
    this.status = 'pending';
    // 成功的值
    this.value = undefined;
    // 失败的原因
    this.reason = undefined;
    
    // 成功回调队列
    this.onFulfilledCallbacks = [];
    // 失败回调队列
    this.onRejectedCallbacks = [];
    
    // 定义resolve方法
    const resolve = (value) => {
      // 只有等待状态才能改变
      if (this.status === 'pending') {
        this.status = 'fulfilled';
        this.value = value;
        
        // 执行所有成功回调
        this.onFulfilledCallbacks.forEach(callback => callback());
      }
    };
    
    // 定义reject方法
    const reject = (reason) => {
      // 只有等待状态才能改变
      if (this.status === 'pending') {
        this.status = 'rejected';
        this.reason = reason;
        
        // 执行所有失败回调
        this.onRejectedCallbacks.forEach(callback => callback());
      }
    };
    
    // 立即执行执行器函数，并捕获错误
    try {
      executor(resolve, reject);
    } catch (error) {
      reject(error);
    }
  }
  
  // then方法实现链式调用
  then(onFulfilled, onRejected) {
    // 处理参数默认值，实现值的穿透
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
    onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason };
    
    // 创建新的Promise用于链式调用
    const promise2 = new MyPromise((resolve, reject) => {
      // 成功状态
      if (this.status === 'fulfilled') {
        // 使用setTimeout模拟异步执行
        setTimeout(() => {
          try {
            const x = onFulfilled(this.value);
            // 处理返回值，实现链式传递
            this.resolvePromise(promise2, x, resolve, reject);
          } catch (error) {
            reject(error);
          }
        }, 0);
      }
      
      // 失败状态
      if (this.status === 'rejected') {
        setTimeout(() => {
          try {
            const x = onRejected(this.reason);
            this.resolvePromise(promise2, x, resolve, reject);
          } catch (error) {
            reject(error);
          }
        }, 0);
      }
      
      // 等待状态，将回调存入队列
      if (this.status === 'pending') {
        this.onFulfilledCallbacks.push(() => {
          setTimeout(() => {
            try {
              const x = onFulfilled(this.value);
              this.resolvePromise(promise2, x, resolve, reject);
            } catch (error) {
              reject(error);
            }
          }, 0);
        });
        
        this.onRejectedCallbacks.push(() => {
          setTimeout(() => {
            try {
              const x = onRejected(this.reason);
              this.resolvePromise(promise2, x, resolve, reject);
            } catch (error) {
              reject(error);
            }
          }, 0);
        });
      }
    });
    
    return promise2;
  }
  
  // 处理then方法返回值的工具方法
  resolvePromise(promise2, x, resolve, reject) {
    // 防止循环引用
    if (promise2 === x) {
      return reject(new TypeError('Chaining cycle detected for promise'));
    }
    
    // 标记是否已经调用过
    let called = false;
    
    // 如果x是对象或函数
    if (x !== null && (typeof x === 'object' || typeof x === 'function')) {
      try {
        // 尝试获取then方法
        const then = x.then;
        
        // 如果then是函数，视为Promise
        if (typeof then === 'function') {
          then.call(
            x,
            y => {
              if (called) return;
              called = true;
              // 递归处理
              this.resolvePromise(promise2, y, resolve, reject);
            },
            r => {
              if (called) return;
              called = true;
              reject(r);
            }
          );
        } else {
          // 不是Promise，直接resolve
          resolve(x);
        }
      } catch (error) {
        if (called) return;
        called = true;
        reject(error);
      }
    } else {
      // 基本类型，直接resolve
      resolve(x);
    }
  }
  
  // catch方法
  catch(onRejected) {
    return this.then(null, onRejected);
  }
  
  // 静态resolve方法
  static resolve(value) {
    return new MyPromise(resolve => {
      resolve(value);
    });
  }
  
  // 静态reject方法
  static reject(reason) {
    return new MyPromise((resolve, reject) => {
      reject(reason);
    });
  }
}

// 使用示例
const promise = new MyPromise((resolve, reject) => {
  setTimeout(() => {
    resolve('成功了');
    // reject('失败了');
  }, 1000);
});

promise
  .then(value => {
    console.log(value);
    return '第一个then的返回值';
  })
  .then(value => {
    console.log(value);
    return new MyPromise(resolve => {
      setTimeout(() => {
        resolve('第二个then中的Promise');
      }, 1000);
    });
  })
  .then(value => {
    console.log(value);
    throw new Error('手动抛出错误');
  })
  .catch(error => {
    console.log(error.message);
  });
